package com.ruoyi.sale.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.finance.domain.ErpFinanceItem;
import com.ruoyi.finance.service.IErpFinanceItemService;
import com.ruoyi.sale.domain.ErpGoodss;
import com.ruoyi.sale.domain.ErpOrder;
import com.ruoyi.sale.domain.ErpProduct;
import com.ruoyi.sale.domain.ErpWarehouseOut;
import com.ruoyi.sale.mapper.ErpOrderMapper;
import com.ruoyi.sale.mapper.ErpWarehouseOutMapper;
import com.ruoyi.sale.service.IErpWarehouseOutService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ErpWarehouseOutServiceImpls implements IErpWarehouseOutService {

    private static final Logger log = LoggerFactory.getLogger(ErpWarehouseOutServiceImpls.class);
    @Autowired
    private ErpOrderMapper erpOrderMapper;

    @Autowired
    private ErpWarehouseOutMapper erpWarehouseOutMapper;

    @Autowired
    private IErpFinanceItemService erpFinanceItemService;

    @Override
    public ErpWarehouseOut selectErpWarehouseOutById(Long id) {
        return erpWarehouseOutMapper.selectErpWarehouseOutById(id);
    }

    @Override
    public List<ErpWarehouseOut> selectErpWarehouseOutList(ErpWarehouseOut erpWarehouseOut) {
        return erpWarehouseOutMapper.selectErpWarehouseOutList(erpWarehouseOut);
    }

    @Override
    public int insertErpWarehouseOut(ErpWarehouseOut erpWarehouseOut) {
        erpWarehouseOut.setCreateTime(DateUtils.getNowDate());
        return erpWarehouseOutMapper.insertErpWarehouseOut(erpWarehouseOut);
    }

    @Override
    public int updateErpWarehouseOut(ErpWarehouseOut erpWarehouseOut) {
        erpWarehouseOut.setUpdateTime(DateUtils.getNowDate());

        // 如果是发货操作
        if ("已发货".equals(erpWarehouseOut.getStatus())) {
            // 1. 更新关联订单状态
            if (StringUtils.isNotEmpty(erpWarehouseOut.getOrderIdList())) {
                String[] orderIds = erpWarehouseOut.getOrderIdList().split(",");
                for (String orderId : orderIds) {
                    ErpOrder order = new ErpOrder();
                    order.setId(Integer.parseInt(orderId));
                    order.setStatus("已发货");
                    order.setShipTime(new Date());
                    erpOrderMapper.updateErpOrder(order);

                    // 2. 扣减库存
                    List<ErpGoodss> goodsList = erpOrderMapper.selectOrderGoodsByOrderId(Long.parseLong(orderId));
                    for (ErpGoodss goods : goodsList) {
                        erpOrderMapper.reduceProductStock(
                                goods.getId(),
                                goods.getCountNum(),
                                erpWarehouseOut.getWarehouseId()
                        );
                        ErpProduct product = new ErpProduct();
                        Map<String, Object> params = new HashMap<>();
                        params.put("warehouseOutId", erpWarehouseOut.getId());
                        params.put("orderId", orderId);
                        params.put("orderSn", order.getSn());
                        params.put("goodsId", goods.getId());
                        params.put("productId", product.getGoods_id());
                        params.put("productName", product.getName());
                        params.put("productSpecification", product.getSpecification());
                        params.put("productPrice", product.getPrice());
                        params.put("outNum", goods.getCountNum());
                        erpWarehouseOutMapper.insertOutItem(params);
                    }

                    // 3. 添加财务记录
                    ErpFinanceItem financeItem = new ErpFinanceItem();
                    financeItem.setSourceType("出库单发货");
                    financeItem.setSourceSn(erpWarehouseOut.getSn());
                    financeItem.setAmount(order.getPayPrice());
                    financeItem.setAmountType("1");
                    erpFinanceItemService.insertErpFinanceItem(financeItem);
                }
            }
        }

        return erpWarehouseOutMapper.updateErpWarehouseOut(erpWarehouseOut);
    }

    @Override
    public int deleteErpWarehouseOutById(Long id) {
        return erpWarehouseOutMapper.deleteErpWarehouseOutById(id);
    }

    @Override
    public int deleteErpWarehouseOutByIds(Long[] ids) {
        return erpWarehouseOutMapper.deleteErpWarehouseOutByIds(ids);
    }

    @Override
    @Transactional
    public int completeOut(Long id) {
        // 1. 更新出库单状态
        ErpWarehouseOut out = erpWarehouseOutMapper.selectErpWarehouseOutById(id);
        if (out == null) {
            throw new RuntimeException("出库单不存在");
        }
        out.setStatus("已完成");
        out.setOutTime(new Date());
        int result = erpWarehouseOutMapper.updateErpWarehouseOut(out);

        // 2. 更新关联订单状态
        if (StringUtils.isNotEmpty(out.getOrderIdList())) {
            String[] orderIds = out.getOrderIdList().split(",");
            for (String orderId : orderIds) {
//                erpOrderMapper.updateOrderStatus(Long.parseLong(orderId), "已完成");
            }
        }

        return result;
    }



    @Override
    @Transactional
    public int addToSalesSummary(Long outId) {
        // 1. 获取出库单信息
        ErpWarehouseOut out = erpWarehouseOutMapper.selectErpWarehouseOutById(outId);
        if (out == null) {
            throw new RuntimeException("出库单不存在");
        }

        // 2. 获取关联订单信息
        if (StringUtils.isEmpty(out.getOrderIdList())) {
            return 0;
        }

        String[] orderIds = out.getOrderIdList().split(",");
        int count = 0;

        for (String orderId : orderIds) {
            // 3. 查询订单详情
            ErpOrder order = erpOrderMapper.selectErpOrderById(Integer.parseInt(orderId));
            if (order != null) {
                // 4. 添加到销售汇总表
                Map<String, Object> params = new HashMap<>();
                params.put("name", order.getOwnerName());
                params.put("num", 1); // 默认数量为1，实际应根据订单商品数量
                params.put("currency", "人民币"); // 默认币种
                params.put("price", order.getPayPrice());
                params.put("tax", order.getTaxPrice());

//                count += erpWarehouseOutMapper.insertSalesSummary(params);
            }
        }

        return count;
    }
    @Override
    public List<Map<String, Object>> getLogisticsCompanies() {
        return erpWarehouseOutMapper.selectLogisticsCompanies();
    }
}
